from collections import Counter, defaultdict


class Solution:

    def maxRepOpt1(self, text: str) -> int:
        h = defaultdict(int)
        l, ans = 0, 0
        cnts = Counter(text)
        for r, t in enumerate(text):
            cnts[t] -= 1
            if len(h) == 2:
                if t not in h:
                    while len(h) == 2:
                        L = text[l]
                        cnts[L] += 1
                        h[L] -= 1
                        if h[L] == 0:
                            h.pop(L)
                        l += 1
                else:
                    o = None
                    for k, v in h.items():
                        if k != t:
                            o = k
                    while h[o] > 1 and h[t] > 0:
                        L = text[l]
                        cnts[L] += 1
                        h[L] -= 1
                        l += 1
            h[t] += 1
            o = None
            if len(h) == 2:
                for k, v in h.items():
                    if k != t:
                        o = k
                cur = r - l
                if h[o] == 1 and h[t] == 1:
                    if cnts[o] != 0 or cnts[t] != 0:
                        cur += 1
                elif h[o] == 1 and cnts[t] != 0:
                    cur += 1
                elif h[t] == 1 and cnts[o] != 0:
                    cur += 1
                ans = max(ans, cur)
            else:
                ans = max(ans, r - l + 1)
        return ans


so = Solution()
print(so.maxRepOpt1("aabbaba"))
# print(so.maxRepOpt1("bbababaaaa"))
# print(so.maxRepOpt1("aabaaabaaaba"))